<?php

use app\job\Write;
use JPush\Client as JPush;

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
error_reporting(E_ALL ^ E_NOTICE);
/**
 * 反转义
 */
function html($str)
{
    return html_entity_decode($str);
}

/**
 * layui分页转换
 */
function layui_page($list)
{
    $list = $list->toArray();
    $list = [
        'code' => 0,
        'msg' => '',
        'data' => $list['data'],
        'count' => $list['total']
    ];
    return $list;
}

/**
 * 字符串转换为数组，主要用于把分隔符调整到第二个参数
 * @param  string $str 要分割的字符串
 * @param  string $glue 分割符
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function str2arr($str, $glue = ',')
{
    return explode($glue, $str);
}

/**
 * 数组转换为字符串，主要用于把分隔符调整到第二个参数
 * @param  array $arr 要连接的数组
 * @param  string $glue 分割符
 * @return string
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function arr2str($arr, $glue = ',')
{
    return implode($glue, $arr);
}

// 自动转换字符集 支持数组转换
function auto_charset($fContents, $from = 'gbk', $to = 'utf-8')
{
    $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
    $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
    if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
        //如果编码相同或者非字符串标量则不转换
        return $fContents;
    }
    if (is_string($fContents)) {
        if (function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($fContents, $to, $from);
        } elseif (function_exists('iconv')) {
            return iconv($from, $to, $fContents);
        } else {
            return $fContents;
        }
    } elseif (is_array($fContents)) {
        foreach ($fContents as $key => $val) {
            $_key = auto_charset($key, $from, $to);
            $fContents[$_key] = auto_charset($val, $from, $to);
            if ($key != $_key)
                unset($fContents[$key]);
        }
        return $fContents;
    } else {
        return $fContents;
    }
}

/**
 * GET 请求
 *
 * @param string $url
 */
function http_get($url, $header = array())
{
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
    }
    curl_setopt($oCurl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus ["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}

/**
 * POST 请求
 *
 * @param string $url
 * @param array $param
 * @return string content
 */
function http_post($url, $param, $header = '')
{
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
    }
    if (is_string($param)) {
        $strPOST = $param;
    } else {
        $aPOST = array();
        foreach ($param as $key => $val) {
            $aPOST [] = $key . "=" . urlencode($val);
        }
        $strPOST = join("&", $aPOST);
    }
    if (is_array($header)) {
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, $header);
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($oCurl, CURLOPT_POST, true);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);
    if (intval($aStatus ["http_code"]) == 200) {
        return $sContent;
    } else {
        return false;
    }
}

/**
 * 对查询结果集进行排序
 * @access public
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param array $sortby 排序类型
 * asc正向排序 desc逆向排序 nat自然排序
 * @return array
 */
function list_sort_by($list, $field, $sortby = 'asc')
{
    if (is_array($list)) {
        $refer = $resultSet = array();
        foreach ($list as $i => $data)
            $refer[$i] = &$data[$field];
        switch ($sortby) {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc':// 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ($refer as $key => $val)
            $resultSet[] = &$list[$key];
        return $resultSet;
    }
    return false;
}

/**
 * 获取图片
 * @param string/int $idarr
 * @param string $field
 * @return 完整的数据  或者  指定的$field字段值
 * @author Gooe <zqscjj@163.com>
 */
function get_img($idarr, $field = '')
{
    if (empty($idarr)) {
        return config('site.domain') . '/static/images/noimage.gif';
    }
    $qiniu_cfg = get_db_config(true)['qiniu_cfg'];
    if (strpos($idarr, ',')) {//多图
        $pictureList = db('Attachment')->where(array('status' => 1, 'id' => array('in', $idarr)))->field($field)->select();
        foreach ($pictureList as $k => $v) {
            if ($v['storage'] == 'local') {
                $pictureList[$k]['path'] = config('site.domain') . $v['url'];
            } else {
                $pictureList[$k]['path'] = $qiniu_cfg['domain'] . '/' . basename($v['url']);
            }
        }
        return $pictureList;
    } else {//单图
        $picture = db('Attachment')->where(array('status' => 1, 'id' => $idarr))->find();
        if ($picture['storage'] == 'local') {
            $picture['path'] = config('site.domain') . $picture['url'];
        } else {
            $picture['path'] = $qiniu_cfg['domain'] . '/' . basename($picture['url']);
        }
        return empty($field) ? $picture['path'] : $picture[$field];
    }

}

/**
 * 替换文章中的图片，将相对路径改为远程路径
 */
function replace_con_img($content)
{
    $pregRule = "/<[img|IMG].*?src=[\'|\"](\/uploads\/ue\/.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
    $content = preg_replace($pregRule, '<img src="' . config('site.domain') . '${1}">', $content);
    return $content;
}

/**
 * 导出excel
 * @param unknown $fileName
 * @param unknown $headArr
 * @param unknown $data
 */
function export_excel($fileName, $headArr, $data, $width = [])
{
    $fileName .= ".xls";
    //创建PHPExcel对象，注意，不能少了\
    $objPHPExcel = new \PHPExcel();
    $objProps = $objPHPExcel->getProperties();
    //设置表头
    $key = ord("A");
    //print_r($headArr);exit;
    foreach ($headArr as $v) {
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $key += 1;
    }
    //设置宽度
    foreach ($width as $k => $v) {
        $objPHPExcel->getActiveSheet()->getColumnDimension($k)->setWidth($v);
    }

    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();
    //print_r($data);exit;
    foreach ($data as $key => $rows) { //行写入
        $span = ord("A");
        foreach ($rows as $keyName => $value) {// 列写入
            $j = chr($span);
            $objActSheet->setCellValue($j . $column, $value);
            $span++;
        }
        $column++;
    }

    $fileName = iconv("utf-8", "gb2312", $fileName);
    //重命名表
    //$objPHPExcel->getActiveSheet()->setTitle('test');
    //设置活动单指数到第一个表,所以Excel打开这是第一个表
    $objPHPExcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header('Cache-Control: max-age=0');

    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output'); //文件通过浏览器下载
    exit;
}

/**
 * xml to array
 * @param unknown $xml
 */
function xml_to_array($xml)
{
    $search = '/<(\w+)\s*?(?:[^\/>]*)\s*(?:\/>|>(.*?)<\/\s*?\\1\s*?>)/s';
    $array = array();
    if (preg_match_all($search, $xml, $matches)) {
        foreach ($matches[1] as $i => $key) {
            $value = $matches[2][$i];
            if (preg_match_all($search, $value, $_matches)) {
                $array[$key] = xml_to_array($value);
            } else {
                if ('ITEM' == strtoupper($key)) {
                    $array[] = html_entity_decode($value);
                } else {
                    $array[$key] = html_entity_decode($value);
                }
            }
        }
    }
    return $array;
}

/**
 * 系统邮件发送函数
 * @param string $tomail 接收邮件者邮箱
 * @param string $name 接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 */
function send_mail($tomail, $name, $subject, $body, $attachment = null)
{
    //获取配置信息
    $mail_config = db('Config')->where([['status', 'neq', '-1'], ['group', '=', '1']])->column('value', 'name');
    $mail = new \PHPMailer\PHPMailer\PHPMailer();
    $mail->CharSet = 'UTF-8';           //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();                    // 设定使用SMTP服务
    $mail->SMTPDebug = 0;               // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
    $mail->SMTPAuth = true;             // 启用 SMTP 验证功能
    switch ($mail_config['mail_smtp']) {
        case '163':
            $mail->SMTPSecure = 'tsl';          // 使用安全协议
            $mail->Host = "smtp.163.com";       // SMTP 服务器
            $mail->Port = 25;                   // SMTP服务器的端口号
            break;
        case 'qq':
            $mail->SMTPSecure = 'ssl';          // 使用安全协议
            $mail->Host = "smtp.qq.com";       // SMTP 服务器
            $mail->Port = 465;                   // SMTP服务器的端口号
            break;
        case 'aliyun':
            $mail->SMTPSecure = 'tsl';          // 使用安全协议
            $mail->Host = "smtp.mxhichina.com";       // SMTP 服务器
            $mail->Port = 25;                   // SMTP服务器的端口号
            break;
    }
    $mail->Username = $mail_config['mail_username'];    // SMTP服务器用户名
    $mail->Password = $mail_config['mail_password'];     // SMTP服务器密码
    //发件信息
    $mail->SetFrom($mail_config['mail_username'], $mail_config['mail_sendname']);
    $replyEmail = '';                   //留空则为发件人EMAIL
    $replyName = '';                    //回复名称（留空则为发件人名称）
    $mail->AddReplyTo($replyEmail, $replyName);
    $tomail = str2arr($tomail);
    foreach ($tomail as $v) {
        $mail->AddAddress($v, $name);
    }

    //内容
    $mail->Subject = $subject;
    //$mail->MsgHTML($body);
    $mail->isHTML(true);
    //html内容
    $mail->Body = $body;
    //这是针对非HTML邮件客户端的纯文本正文。
    $mail->AltBody = 'so sorry! 您的客户端不支持！';

    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}

/**
 * 是否为手机浏览器
 */
function is_mobile()
{
    // 先检查是否为wap代理，准确度高
    if (stristr($_SERVER['HTTP_VIA'], "wap")) {
        return true;
    } // 检查浏览器是否接受 WML.
    elseif (strpos(strtoupper($_SERVER['HTTP_ACCEPT']), "VND.WAP.WML") > 0) {
        return true;
    } //检查USER_AGENT
    elseif (preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $_SERVER['HTTP_USER_AGENT'])) {
        return true;
    } else {
        return false;
    }
}

/**
 * 解析获取php.ini 的upload_max_filesize（单位：byte）
 * @param $dec int 小数位数
 * @return float （单位：byte）
 * */
function get_upload_max_filesize_byte($dec = 2)
{
    $max_size = ini_get('upload_max_filesize');
    preg_match('/(^[0-9\.]+)(\w+)/', $max_size, $info);
    $size = $info[1];
    $suffix = strtoupper($info[2]);
    $a = array_flip(array("B", "KB", "MB", "GB", "TB", "PB"));
    $b = array_flip(array("B", "K", "M", "G", "T", "P"));
    $pos = $a[$suffix] && $a[$suffix] !== 0 ? $a[$suffix] : $b[$suffix];
    return round($size * pow(1024, $pos), $dec);
}

/**
 * 发送阿里大于短信
 */
function send_sms($mobile, $code, $type = '', $tpl_name = '', $sign_name = '', $uid = null)
{
    $config = db('Config')->where('status', 'neq', -1)->where('group', '2')->cache('__ALISMS_CONFIG__')->column('value', 'name');
    $sms_config = [
        'accessKeyId' => $config['alisms_accessKeyId'],
        'accessKeySecret' => $config['alisms_accessKeySecret'],
    ];
    if (empty($sign_name)) $sign_name = $config['alisms_sign_name'];
    //$tpl_name = 'alisms_tpl_'.$type;
    if (empty($tpl_name))
        $tpl_name = 'alisms_tpl_reglogin';

    $tpl = $config[$tpl_name];

    $client = new \Flc\Dysms\Client($sms_config);
    $sendSms = new Flc\Dysms\Request\SendSms;
    $sendSms->setPhoneNumbers($mobile);
    $sendSms->setSignName($sign_name);
    $sendSms->setTemplateCode($tpl);
    $sendSms->setTemplateParam($code);
    //$sendSms->setOutId('demo');
    $re = $client->execute($sendSms);
    //记录日志
    if ($re['Code'] == 'OK') {
        $sms = model('Sms');
        $sms->uid = $uid;
        $sms->mobile = $mobile;
        $sms->code = json_encode($code);
        $sms->bizid = $re['BizId'];
        $sms->type = $type;
        $sms->save();
    }
    return $re;
}

/**
 * 获取优惠券面额数字
 */
function get_coupon_price($str)
{
    //preg_match($pattern, $subject);
    return _cut('减', '元', $str);
}

/**
 * php截取指定两个字符之间字符串，默认字符集为utf-8 Power by 大耳朵图图
 * @param string $begin 开始字符串
 * @param string $end 结束字符串
 * @param string $str 需要截取的字符串
 * @return string
 */
function _cut($begin, $end, $str)
{
    $b = mb_strpos($str, $begin) + mb_strlen($begin);
    $e = mb_strripos($str, $end) - $b;

    return mb_substr($str, $b, $e);
}

/**
 * 生成随机唯一邀请码/优惠码固定长度
 */
function make_invite_code()
{
    $letters = str_shuffle('ABCDEFGHJKMNPQRSTUVWXY');
    $numbers = str_shuffle('13456789');
    return substr($letters, 0, 2) . substr($numbers, 0, 4);
}

/**
 * 获取数据库的里的配置信息
 */
function get_db_config($arr = false)
{
    $cfg = db('Config')->where('status', 'neq', -1)->cache('db_config')->column('value', 'name');
    if ($arr) {
        foreach ($cfg as $k => $v) {
            if (is_array(json_decode($v, true)))
                $cfg[$k] = json_decode($v, true);
        }
    }
    return $cfg;
}

/**
 * 增加用户财富函数
 * @param string $name 财富标识名
 * @param int $lock_time解锁时间，即多长时间内才能重复加积分，为0时不作控制
 * @param array $score
 *  自定义积分值，格式：array('money'=>余额,'score'=>积分,'experience'=>经验值);为空时默认取管理中心积分管理里的配置值
 */
function add_money($name, $uid, $money = array(), $admin_uid = 0, $lock_time = 0)
{
    if (empty ($name) && empty ($uid))
        return false;
    if ($lock_time > 0) {
        $key = 'money_lock__' . $uid . '_' . $name;
        if (cache($key))
            return false;
        cache($key, 1, $lock_time);
    }
    //冻结的用户不给加钱
    //         $status = db('user')->where('uid',$uid)->value('status');
    //         if ($status==0 && $money>0){
    //             return true;
    //         }
    $data = [];
    $data ['uid'] = $uid;
    $data ['type'] = $name;
    $data ['admin_uid'] = $admin_uid;
    $data = array_merge($data, $money);
    $res = model('common/MoneyLogs')->add_money($data);
    return $res;
}

/**
 * 增加减用户积分
 */
function add_score($name, $uid, $money = array(), $admin_uid = 0, $lock_time = 0)
{
    if (empty ($name) && empty ($uid))
        return false;
    if ($lock_time > 0) {
        $key = 'score_lock__' . $uid . '_' . $name;
        if (cache($key))
            return false;
        cache($key, 1, $lock_time);
    }
    //冻结的用户不给加钱
    //         $status = db('user')->where('uid',$uid)->value('status');
    //         if ($status==0 && $money['score']>0){
    //             return true;
    //         }
    $data = [];
    $data ['uid'] = $uid;
    $data ['type'] = $name;
    $data ['admin_uid'] = $admin_uid;
    $data = array_merge($data, $money);
    $res = model('common/ScoreLogs')->add_money($data);;
    return $res;
}

/**
 * 获取用户nickname
 */
function get_nickname($uid)
{
    return db('User')->where('uid', $uid)->cache('nickname_' . $uid)->value('nickname');
}

/**
 * 生成唯一订单号毫秒+6个随机数，26位
 */
function build_order_no()
{
    $no = date('YmdHis') . substr(microtime(), 2, 6) . \ddj\Random::numeric(6);

    return $no;
}


/**
 * 导淘宝订单,队列处理
 * 需要分两个任务，一个是创建时间，一个是结算时间
 * 递归,线上建议只查1分钟内定单，每分钟查一次;以避免重复取数据
 * order_query_type:订单查询类型，创建时间“create_time”，或结算时间“settle_time”
 */
function import_order_tb($span, $order_query_type = 'create_time', $start_time = '', $page_no = 1)
{
    $db_config = get_db_config(true);
    $mm_id = $db_config['tk_cfg']['taobao']['id'];
    $options = [
        'page_no' => $page_no,
        'page_size' => 100,
        'order_query_type' => $order_query_type,
    ];
    $tk = new \ddj\Tk($options);
    $re = $tk->import_order($span, $start_time);
    if ($re['errcode'] == 0) {
        $data = $re['data'] ?? [];
        if (count($data) > 0) {
            //导入数据
            $job_write = new Write();
            foreach ($data as $k => $v) {
                $mm_pid = 'mm_' . $mm_id . '_' . $v['site_id'] . '_' . $v['adzone_id'];
                $order_status_arr = [12 => 1, 3 => 2, 13 => 3, 14 => 4];
                $temp = [
                    'tjp' => 't',
                    'title' => $v['item_title'],
                    'item_id' => (string)$v['num_iid'],
                    'shop_tile' => $v['seller_shop_title'],
                    'item_num' => $v['item_num'],
                    'price' => $v['price'],
                    'pay_price' => $v['pay_price'] == 0 ? $v['alipay_total_price'] : $v['pay_price'],
                    'order_status' => $order_status_arr[$v['tk_status']],
                    'order_type' => $v['order_type'] == '天猫' ? 1 : 0,
                    'income_rate' => $v['income_rate'] * 100,
                    'income_price' => $v['pub_share_pre_fee'],
                    'trade_id' => $v['trade_id'],
                    'trade_parent_id' => $v['trade_parent_id'],
                    'cate_title' => $v['auction_category'],
                    'site_name' => $v['site_name'] . '/' . $v['adzone_name'],
                    'build_time' => strtotime($v['create_time']),
                    'end_time' => isset($v['earning_time']) ? strtotime($v['earning_time']) : 0,
                    'p_id' => $mm_pid,
                ];
                //dump($temp);die;
                //全部仍进队列，慢慢处理
                $job_write->import_order($temp);
            }
            if (count($data) == $options['page_size']) {
                $page_no++;
                import_order_tb($span, $order_query_type, $start_time, $page_no);
            }
        }

    }

}

/**
 * 导入京东订单
 */
function import_order_jd($start_time, $page_no = 1)
{
    $options = [
        'page_no' => $page_no,
        'page_size' => 100,
    ];
    //接口查询
    $jd = new \ddj\Jd($options);
    $re = $jd->import_order($start_time);

    if ($re['code'] == 200) {
        $data = $re['data'] ?? [];
        if (count($data) > 0) {
            //导入数据
            $job_write = new Write();
            foreach ($data as $k => $v) {
                foreach ($v['skuList'] as $kk => $vv) {
                    //$mm_pid = 'mm_'.$mm_id.'_'.$v['site_id'].'_'.$v['adzone_id'];
                    $order_status_arr = [16 => 1, 18 => 2, 17 => 4];//付款，完成，结算三种订单,其它均为无效
                    $temp = [
                        'tjp' => 'j',
                        'title' => $vv['skuName'],
                        'item_id' => (string)$vv['skuId'],
                        'shop_tile' => '',
                        'item_num' => $vv['skuNum'],
                        'price' => $vv['price'],
                        'pay_price' => $vv['estimateCosPrice'],
                        'order_status' => $order_status_arr[$vv['validCode']] ?? 3,
                        'order_type' => 2,
                        'income_rate' => $vv['commissionRate'],
                        'income_price' => $vv['estimateFee'],
                        'trade_id' => (string)$v['orderId'] . '-' . (string)$vv['skuId'],//修复订单号重复的问题
                        'trade_parent_id' => (string)$v['parentId'],
                        'cate_title' => '',
                        'site_name' => '',
                        'build_time' => substr($v['orderTime'], 0, -3),
                        'end_time' => ($v['finishTime'] > 0) ? substr($v['finishTime'], 0, -3) : 0,
                        'p_id' => $vv['positionId'],
                    ];
                    //全部仍进队列，慢慢处理
                    $job_write->import_order($temp);
                }

            }
            if ($re['hasMore']) {
                $page_no++;
                import_order_jd($start_time, $page_no);
            }
        }

    }
}

/**
 * 导单-拼多多
 * 第几页，从1到10000，默认1，注：使用最后更新时间范围增量同步时，必须采用倒序的分页方式（从最后一页往回取）才能避免漏单问题。
 */
function import_order_pdd($start_time, $page_no = 1, $i = 0)
{
    $options = [
        'type' => 'pdd.ddk.order.list.increment.get',
        'start_update_time' => $start_time,
        'end_update_time' => time(),
        'page_no' => $page_no,
        'page_size' => 100,
    ];
    //接口查询
    $pdd = new \ddj\Pdd($options);
    $res = $pdd->request();
    $list = $res['order_list_get_response']['order_list'];
    if ($i == 0) {
        $page_no = ceil($res['order_list_get_response']['total_count'] / $options['page_size']);
    }
    if ($res['order_list_get_response']['total_count'] > 0) {
        $i++;
        //导入数据
        $job_write = new Write();
        foreach ($list as $k => $v) {
            //订单状态对应
            //0和2和3对应1，已经支付，5对应2结算，4对应3成功，-1和8不导入
            if ($v['order_status'] != -1 && $v['order_status'] != 8) {
                $order_status_arr = [5 => 2, 4 => 3, 4 => 3];
                if (in_array($v['order_status'], [0, 1, 2, 3])) {
                    $order_status = 1;
                } else {
                    $order_status = $order_status_arr[$v['order_status']];
                }
                $temp = [
                    'tjp' => 'p',
                    'title' => $v['goods_name'],
                    'item_id' => (string)$v['goods_id'],
                    'pic' => $v['goods_thumbnail_url'],
                    'shop_tile' => '',
                    'item_num' => $v['goods_quantity'],
                    'price' => $v['goods_price'] / 100,
                    'pay_price' => $v['order_amount'] / 100,
                    'order_status' => $order_status,
                    'order_type' => 3,
                    'income_rate' => $v['promotion_rate'] / 10,
                    'income_price' => $v['promotion_amount'] / 100,
                    'trade_id' => $v['order_sn'],
                    'trade_parent_id' => 0,
                    'cate_title' => '',
                    'site_name' => '',
                    'build_time' => $v['order_create_time'],
                    'end_time' => $v['order_modify_at'],
                    'p_id' => $v['custom_parameters'],
                ];
                //全部仍进队列，慢慢处理
                $job_write->import_order($temp);
            }

        }
        if ($page_no > 2) {
            $page_no--;
            import_order_pdd($start_time, $page_no, $i);
        }
    }
}

/**
 * 订单-分佣计算
 * 1.除了分公司外，其它等级平级不分润
 * 2.达人自购时不会再次额外抽取
 */
function fenyong_order($order_id, $uid, $money, $tjp = 't', $is_share = 0, $i = -1, $has_get_lv = [], $buy_uid = 0)
{
    $db_config = get_db_config(true);
    $lvcfg = $db_config['user_leval_cfg'];
    //实际应分的钱数
    $kengdie_fee = $lvcfg['kengdie_fee'] ?? 0;
    $kengdie_fee = intval($kengdie_fee);
    $money_real = $money * (100 - $kengdie_fee) / 100;
    //防止重复分钱
    if ($i == -1) {
        $logs = db('orders_money')->where('order_id', $order_id)->find();
        if ($logs) {
            return false;
        }
        $buy_uid = $uid;
    }
    $uinfo = db('user')->where('uid', $uid)->field('uid,pid,leval')->find();
    if ($uinfo) {
        $bool = true;//是否继续找
        $i++;
        if ($i == 0) {//自己
            $get_money = 0;
            $j1_name = 'zigou';
            if ($is_share == 1) $j1_name = 'share';
            $j1_cfg = $lvcfg[$j1_name];
            //当前等级分佣比例
            $j1_per = floatval($j1_cfg[$uinfo['leval']]);
            //得到的钱
            $get_money = $money_real * $j1_per / 100;
            if ($get_money > 0) {
                $money_logs = [
                    'order_id' => $order_id,
                    'uid' => $uid,
                    'leval' => $uinfo['leval'],
                    'money' => $get_money,
                    'is_share' => $is_share,
                    'per' => $j1_per,
                    'buy_uid' => $buy_uid,
                    'tjp' => $tjp,
                ];
                $money_logs['create_time'] = $money_logs['update_time'] = time();
                //dump($money_logs);
                //插入
                db('orders_money')->insert($money_logs);
                //推送消息
                $format_time = date('Y-m-d H:i:s');
                sendJpush($uid, "您在{$format_time} 购买成功，预估佣金:{$get_money}元");
            }

            //$has_get_lv[$i] = $uinfo['leval'];dump($has_get_lv);
        } elseif ($i == 1 && $uinfo['leval'] > 0) {//上级
            //如果已经有达人以上得到过不再得
            $get_money = 0;
            //如果下级是多多客，正常得钱
            if ($has_get_lv[0] === 0) {
                $j2_name = '0gouwu';
                if ($is_share == 1) $j2_name = '0share';
                $j2_cfg = $lvcfg[$j2_name];
                //当前等级分佣比例
                $j2_per = floatval($j2_cfg[$uinfo['leval']]);
                //得到的钱
                $get_money = $money_real * $j2_per / 100;
                if ($get_money > 0) {
                    $money_logs = [
                        'order_id' => $order_id,
                        'uid' => $uid,
                        'leval' => $uinfo['leval'],
                        'money' => $get_money,
                        'is_share' => $is_share,
                        'per' => $j2_per,
                        'buy_uid' => $buy_uid,
                        'tjp' => $tjp,
                    ];
                    $money_logs['create_time'] = $money_logs['update_time'] = time();
                    //dump($money_logs);
                    //插入
                    db('orders_money')->insert($money_logs);
                    //推送消息
                    $fans_nickname = get_nickname($buy_uid);
                    $format_time = date('Y-m-d H:i:s');
                    sendJpush($uid, "您的粉丝\"{$fans_nickname}\"在{$format_time} 推广成功，预估佣金:{$get_money}元");
                }
            } else {
                //否则达人得无限级的提成，公司一样，此时买手不得钱了
                $per = 0;
                if ($uinfo['leval'] == 2) {//达人无限级
                    $per = floatval($lvcfg['ngouwu'][2]);
                } elseif ($uinfo['leval'] == 3) {
                    $per = floatval($lvcfg['ngouwu'][3][1]);
                }
                $get_money = $money_real * $per / 100;
                if ($get_money > 0) {
                    $money_logs = [
                        'order_id' => $order_id,
                        'uid' => $uid,
                        'leval' => $uinfo['leval'],
                        'money' => $get_money,
                        'is_share' => $is_share,
                        'per' => $per,
                        'buy_uid' => $buy_uid,
                        'tjp' => $tjp,
                    ];
                    $money_logs['create_time'] = $money_logs['update_time'] = time();
                    //dump($money_logs);
                    //插入
                    db('orders_money')->insert($money_logs);
                    //推送消息
                    $fans_nickname = get_nickname($buy_uid);
                    $format_time = date('Y-m-d H:i:s');
                    sendJpush($uid, "您的粉丝\"{$fans_nickname}\"在{$format_time} 推广成功，预估佣金:{$get_money}元");
                }
            }
            //$has_get_lv[$i] = $uinfo['leval'];
        } else {
            $get_money = 0;
            $per = 0;
            //达人，如果前面没有达人得钱，才得钱
            if (!in_array(2, $has_get_lv) && $uinfo['leval'] == 2) {
                $per = floatval($lvcfg['ngouwu'][3][1]);
            }
            //分公司
            $count_arr = array_count_values($has_get_lv);
            $companay_count = $count_arr[3] ?? 0;
            if ($uinfo['leval'] == 3 && $companay_count <= 2) {
                if ($companay_count == 0) {
                    $per = floatval($lvcfg['ngouwu'][3][1]);
                } elseif ($companay_count == 1) {
                    $per = floatval($lvcfg['ngouwu'][3][2]);
                } elseif ($companay_count == 2) {
                    $per = floatval($lvcfg['ngouwu'][3][3]);
                }
            }
            $get_money = $money_real * $per / 100;
            if ($get_money > 0) {
                $money_logs = [
                    'order_id' => $order_id,
                    'uid' => $uid,
                    'leval' => $uinfo['leval'],
                    'money' => $get_money,
                    'is_share' => $is_share,
                    'per' => $per,
                    'buy_uid' => $buy_uid,
                    'tjp' => $tjp,
                ];
                $money_logs['create_time'] = $money_logs['update_time'] = time();
                //dump($money_logs);
                //插入
                db('orders_money')->insert($money_logs);
                //推送消息
                $fans_nickname = get_nickname($buy_uid);
                $format_time = date('Y-m-d H:i:s');
                sendJpush($uid, "您的粉丝\"{$fans_nickname}\"在{$format_time} 推广成功，预估佣金:{$get_money}元");
            }
            //找到三个公司即停止
            if ($companay_count == 2 && $uinfo['leval'] == 3) {
                $bool = false;
            }
        }
        $has_get_lv[$i] = $uinfo['leval'];
        //递归
        if ($bool) {
            fenyong_order($order_id, $uinfo['pid'], $money, $tjp, $is_share, $i, $has_get_lv, $buy_uid);
        }


    }

}

/**
 * 返利
 */
function fanli()
{
    //set_time_limit(0);
    $lvcfg = get_db_config(true)['user_leval_cfg'];
    $js_type = intval($lvcfg['order_jiesuan_type']);
    $js_time = $lvcfg['order_jiesuan_time'];
    $list_ids = [];
    if ($js_type == 0) {//每月某天结算上月的订单
        if (date('d') != $js_time) {
            return false;
        }
        //结算订单
        $list_ids = model('Orders')->field('id')->where('is_fanli', 0)->where('order_status', 2)->where('status', 1)->whereTime('end_time', 'last month')->limit(500)->select();
    } elseif ($js_type == 1) {//订单结算后多少天
        $list_ids = model('orders')->field('id')->where('is_fanli', 0)->where('order_status', 2)->where('status', 1)->whereTime('end_time', '<=', time() - 86400 * $js_time)->limit(500)->select();
    } else {
        return false;
    }
    //dump($list_ids);
    $list_ids = $list_ids ?? [];
    //开始结算,扔进队列
    if (count($list_ids) > 0) {
        //全部仍进队列，一条条处理
        $job_write = new Write();
        foreach ($list_ids as $k => $v) {
            $data = [
                'queue_type' => 'fanli',
                'order_id' => $v['id']
            ];
            if ($job_write->import_order($data)) {
                $v->is_fanli = 1;
                $v->save();
            }
        }
        return true;
    } else {
        return false;
    }
}

/**
 * 支付成功分脏,代理分佣
 * 只有两级，无需递归
 * payitem 1是礼包奖，2是月付推荐奖
 */
function fenyong_leval($payitem, $uid, $money)
{
    $db_config = get_db_config(true);
    $lvcfg = $db_config['user_leval_cfg'];
    $uinfo = db('user')->where('uid', $uid)->field('uid,pid,leval')->find();//自己
    if ($uinfo) {
        $p1info = db('user')->where('uid', $uinfo['pid'])->field('uid,pid,leval')->find();//第上一级
        if ($p1info) {
            if ($p1info['leval'] > 0/*  && $p1info['leval']>=$uinfo['leval'] */) {//上级必须要大于或等于下级
                $get_money = 0;
                if ($payitem == 1) {//礼包推荐奖
                    $get_money = round(floatval($lvcfg['libao'][$p1info['leval']][1]), 2);//这里是元
                    $money_name = 'fenyong_leval_1';
                } else {
                    $get_money = round(floatval($lvcfg['yuefu'][$p1info['leval']][1]) / 100 * $money, 2);//这里是百分比
                    $money_name = 'fenyong_leval_2';
                }
                if ($get_money > 0) {
                    //dump($p1info['uid'].'--得钱--'.$get_money);
                    add_money($money_name, $p1info['uid'], ['money' => $get_money, 'remark' => '', 'attach' => $uid]);
                }
            }
            $p2info = db('user')->where('uid', $p1info['pid'])->field('uid,pid,leval')->find();//第上二级
            if ($p2info) {
                if ($p2info['leval'] > 0/*  && $p2info['leval']>=$uinfo['leval'] */) {
                    $get_money = 0;
                    if ($payitem == 1) {//礼包推荐奖
                        $get_money = round(floatval($lvcfg['libao'][$p2info['leval']][2]), 2);//这里是元
                        $money_name = 'fenyong_leval_1';
                    } else {
                        $get_money = round(floatval($lvcfg['yuefu'][$p2info['leval']][2]) / 100 * $money, 2);//这里是百分比
                        $money_name = 'fenyong_leval_2';
                    }
                    if ($get_money > 0) {
                        //dump($p2info['uid'].'--得钱--'.$get_money);
                        add_money($money_name, $p2info['uid'], ['money' => $get_money, 'remark' => '', 'attach' => $uid]);
                    }
                }
            }
        }
    }

}

/**
 * 自动升级
 * @pid 上级的id
 * @lv 要升级的等级
 * 普通用户是无法升级的
 * 升级只能一级一级的升，不能跳级
 */
function auto_leval_up($pid)
{
    $db_config = get_db_config(true);
    $lvcfg = $db_config['user_leval_cfg'];
    $pinfo = db('user')->where('uid', $pid)->find();
    if ($pinfo) {
        if ($pinfo['leval'] < 3 && $pinfo['leval'] > 0) {
            //一级级的升,会员升级vip
            if ($pinfo['leval'] == 1) {
                $son_lv1_count = db('user')->where('pid', $pid)->where('leval', 1)->count();
                if ($son_lv1_count >= intval($lvcfg['leval_condition'][2][1]) && intval($lvcfg['leval_condition'][2][1]) > 0) {
                    $data = [
                        'leval' => 2,
                        'last_leval_time' => time(),
                        'leval_end_time' => 0,//有效期
                    ];
                    db('user')->where('uid', $pid)->update($data);
                }

            }
            //vip升分公司
            if ($pinfo['leval'] == 2) {
                $son_lv2_count = db('user')->where('pid', $pid)->where('leval', 2)->count();
                if ($son_lv2_count >= intval($lvcfg['leval_condition'][3][1]) && intval($lvcfg['leval_condition'][3][1]) > 0) {
                    $data = [
                        'leval' => 3,
                        'last_leval_time' => time(),
                        'leval_end_time' => 0,//有效期
                    ];
                    db('user')->where('uid', $pid)->update($data);
                }
            }
        }
    }

}

/**
 * 检测等级是否过期,如果到期，直接降至最低等级
 */
function check_leval($uid = null)
{
    if ($uid) {
        $list = model('user')->where('uid', $uid)->where('leval_end_time', '>', 0)->where('leval_end_time', '<', time())->select();
    } else {
        $list = model('user')->where('leval_end_time', '>', 0)->where('leval_end_time', '<', time())->select();
    }
    $list = $list ?? [];
    if (count($list) > 0) {
        foreach ($list as $k => $v) {
            $v->leval = 0;
            $v->leval_end_time = 0;
            $v->save();
        }
    }
}

/**
 * 邀请好友注册送积分
 */
function score_invite($pid)
{
    $db_config = get_db_config(true);
    $get_score = (int)$db_config['user_leval_cfg']['score']['invite'];
    if ($get_score > 0) {
        add_money('invite', $pid, ['score' => $get_score, 'remark' => '好友注册']);
    }
}


function get_redis()
{

    $host = config('cache.host');
    $password = config('cache.password');

    $redis = new \Redis();
    $redis->connect($host, 6379);
    $redis->auth($password);

    return $redis;
}

/**
 * 完成任务送积分
 */
function add_task_score($action, $uid)
{
    $db_config = get_db_config(true);
    $task_cfg = $db_config['user_leval_cfg']['score']['task'];
    switch ($action) {
        //新手任务
        case 1://购买n个有效订单
            if ($task_cfg['newuser'][1]['condition'] > 0 && $task_cfg['newuser'][1]['reward'] > 0) {
                //并没有得到过
                if (!db('score_logs')->where(['uid' => $uid, 'type' => 'task_newuser', 'attach' => 1])->find()) {
                    $count = model('Orders')->where('uid', $uid)->where('is_share', 0)->where('order_status', 'not in', '3,5')->count();
                    if ($count >= $task_cfg['newuser'][1]['condition']) {
                        add_score('task_newuser', $uid, ['score' => $task_cfg['newuser'][1]['reward'], 'remark' => '新手任务:购买', 'attach' => 1]);
                    }
                }
            }
            break;
        case 2://分享购买n个有效订单
            if ($task_cfg['newuser'][2]['condition'] > 0 && $task_cfg['newuser'][2]['reward'] > 0) {
                //并没有得到过
                if (!db('score_logs')->where(['uid' => $uid, 'type' => 'task_newuser', 'attach' => 2])->find()) {
                    $count = model('Orders')->where('uid', $uid)->where('is_share', 1)->where('order_status', 'not in', '3,5')->count();
                    if ($count >= $task_cfg['newuser'][2]['condition']) {
                        add_score('task_newuser', $uid, ['score' => $task_cfg['newuser'][2]['reward'], 'remark' => '新手任务:分享购买', 'attach' => 2]);
                    }
                }
            }
            break;
        case 3://完成n次app分享
            if ($task_cfg['newuser'][3]['condition'] > 0 && $task_cfg['newuser'][3]['reward'] > 0) {
                //并没有得到过
                if (!db('score_logs')->where(['uid' => $uid, 'type' => 'task_newuser', 'attach' => 3])->find()) {
                    $count = model('ShareLogs')->where(['uid' => $uid, 'type' => 0])->count();
                    if ($count >= $task_cfg['newuser'][3]['condition']) {
                        add_score('task_newuser', $uid, ['score' => $task_cfg['newuser'][3]['reward'], 'remark' => '新手任务:分享app', 'attach' => 3]);
                    }
                }
            }
            break;
        case 4://完成n次商品分享
            if ($task_cfg['newuser'][4]['condition'] > 0 && $task_cfg['newuser'][4]['reward'] > 0) {
                //并没有得到过
                if (!db('score_logs')->where(['uid' => $uid, 'type' => 'task_newuser', 'attach' => 4])->find()) {
                    $count = model('ShareLogs')->where(['uid' => $uid, 'type' => 1])->count();
                    if ($count >= $task_cfg['newuser'][4]['condition']) {
                        add_score('task_newuser', $uid, ['score' => $task_cfg['newuser'][4]['reward'], 'remark' => '新手任务:分享商品', 'attach' => 4]);
                    }
                }
            }
            break;
        case 5://邀请n位有效粉丝
            if ($task_cfg['newuser'][5]['condition'] > 0 && $task_cfg['newuser'][5]['reward'] > 0) {
                //并没有得到过
                if (!db('score_logs')->where(['uid' => $uid, 'type' => 'task_newuser', 'attach' => 5])->find()) {
                    $count = model('User')->where('pid', $uid)->count();
                    if ($count >= $task_cfg['newuser'][5]['condition']) {
                        add_score('task_newuser', $uid, ['score' => $task_cfg['newuser'][5]['reward'], 'remark' => '新手任务:邀请粉丝', 'attach' => 5]);
                    }
                }
            }
            break;
        case 6://首次购买会员
            if ($task_cfg['newuser'][6]['reward'] > 0) {
                //并没有得到过
                if (!db('score_logs')->where(['uid' => $uid, 'type' => 'task_newuser', 'attach' => 6])->find()) {
                    $count = model('Paylogs')->where('uid', $uid)->where('pay_status', 1)->count();
                    if ($count > 0) {
                        add_score('task_newuser', $uid, ['score' => $task_cfg['newuser'][6]['reward'], 'remark' => '新手任务:首次购买会员', 'attach' => 6]);
                    }
                }
            }
            break;
        //每日任务
        case 7://浏览n件商品
            if ($task_cfg['days'][7]['condition'] > 0 && $task_cfg['days'][7]['reward'] > 0) {
                //今天没有得到过
                if (!db('score_logs')->where(['uid' => $uid, 'type' => 'task_days', 'attach' => 7])->whereTime('create_time', 'today')->find()) {
                    $count = db('goods_logs')->where(['uid' => $uid, 'is_collect' => 0])->whereTime('create_time', 'today')->count();
                    if ($count >= $task_cfg['days'][7]['condition']) {
                        add_score('task_days', $uid, ['score' => $task_cfg['days'][7]['reward'], 'remark' => '每日任务:浏览商品', 'attach' => 7]);
                    }
                }
            }
            break;
        case 8://完成n次app分享
            if ($task_cfg['days'][8]['condition'] > 0 && $task_cfg['days'][8]['reward'] > 0) {
                //今天没有得到过
                if (!db('score_logs')->where(['uid' => $uid, 'type' => 'task_days', 'attach' => 8])->whereTime('create_time', 'today')->find()) {
                    $count = model('ShareLogs')->where(['uid' => $uid, 'type' => 0])->whereTime('create_time', 'today')->count();
                    if ($count >= $task_cfg['days'][8]['condition']) {
                        add_score('task_days', $uid, ['score' => $task_cfg['days'][8]['reward'], 'remark' => '每日任务:分享app', 'attach' => 8]);
                    }
                }
            }
            break;
        case 9://完成n次商品分享
            if ($task_cfg['days'][9]['condition'] > 0 && $task_cfg['days'][9]['reward'] > 0) {
                //今天没有得到过
                if (!db('score_logs')->where(['uid' => $uid, 'type' => 'task_days', 'attach' => 9])->whereTime('create_time', 'today')->find()) {
                    $count = model('ShareLogs')->where(['uid' => $uid, 'type' => 1])->whereTime('create_time', 'today')->count();
                    if ($count >= $task_cfg['days'][9]['condition']) {
                        add_score('task_days', $uid, ['score' => $task_cfg['days'][9]['reward'], 'remark' => '每日任务:商品分享', 'attach' => 9]);
                    }
                }
            }
            break;
        case 10://邀请n位有效粉丝
            if ($task_cfg['days'][10]['condition'] > 0 && $task_cfg['days'][10]['reward'] > 0) {
                //今天没有得到过
                if (!db('score_logs')->where(['uid' => $uid, 'type' => 'task_days', 'attach' => 10])->whereTime('create_time', 'today')->find()) {
                    $count = model('User')->where('pid', $uid)->whereTime('create_time', 'today')->count();
                    if ($count >= $task_cfg['days'][10]['condition']) {
                        add_score('task_days', $uid, ['score' => $task_cfg['days'][10]['reward'], 'remark' => '每日任务:邀请粉丝', 'attach' => 10]);
                    }
                }
            }
            break;
        case 11://邀请好友购买会员
            if ($task_cfg['days'][11]['reward'] > 0) {
                //今天没有得到过
                if (!db('score_logs')->where(['uid' => $uid, 'type' => 'task_days', 'attach' => 11])->whereTime('create_time', 'today')->find()) {
                    $myfans = model('User')->where('pid', $uid)->column('uid');
                    if ($myfans) {
                        $count = model('Paylogs')->where('uid', 'in', $myfans)->where('pay_status', 1)->whereTime('create_time', 'today')->count();
                        if ($count > 0) {
                            add_score('task_days', $uid, ['score' => $task_cfg['days'][11]['reward'], 'remark' => '每日任务:邀请好友购买会员', 'attach' => 11]);
                        }
                    }
                }
            }
            break;
        default:
            break;
    }
}


/**
 * 成为下线通知
 * @param $pid
 * @param $data [pid, nickname]
 * @param $pUinfo
 */
function pushOffline($pid, $data)
{

    $pUinfo = db('User')->where('uid', $data['pid'])->find();

    if ($pUinfo) {

        // 发通知
        $redis = get_redis();
        $pushText = "亲爱的{$pUinfo['nickname']}，{$data['nickname']}已成为您的粉丝，快去看看吧";

        $redis->lPush("JPUSH-SEND-LIST", json_encode([
            'send_type' => 'sendOne',
            'send_data' => [
                'alert' => $pushText,
                'uid' => $pid,
                'nickname' => $pUinfo['nickname']
            ]]));
    }
}

/**
 * 成为下线通知
 * @param $money
 * @param $regid
 */
function pushMoneyIncrease($money, $uid)
{
    $pushText = "您有一笔： {$money} 已到账，快去看看吧！";
    return pushOne($pushText, $uid);
}

/**
 * 下单成功通知本人
 * @param $trade_id 订单号
 * @param $regid
 */
function pushOrderSuccess($trade_id, $uid)
{
    $good_name = db('Orders')->where('trade_parent_id', $trade_id)
        ->whereOr('trade_id', $trade_id)->value('title');
    $pushText = "{$good_name}，付费成功，收货后佣金会自动转账到账户！";
    return pushOne($pushText, $uid);
}

/**
 * 下单成功通知上线
 * @param $uinfo 用户
 */
function pushOrderSuccessUp($uinfo)
{
    if ($uinfo->pid) {
        return pushOne("您的下级 '{$uinfo->nickname}' 下单成功,您的预估佣金为：***", $uinfo->uid);
    }
}

function pushOne($text, $uid)
{
    get_redis()->lPush("JPUSH-SEND-LIST", json_encode([
        'send_type' => 'sendOne',
        'send_data' => [
            'alert' => $text,
            'uid' => $uid,
            'nickname' => db('User')->where('uid', $data['uid'])->value('nickname'),
        ]
    ]));
}

function pushByRegid($text, $regid)
{
    if ($regid === null) {
        return false;
    }
    $sendByRegid = [
        'send_type' => 'sendByRegid',
        'send_data' => [
            'alert' => $text,
            'jpush_regid' => $regid
        ]
    ];
    get_redis()->lPush("JPUSH-SEND-LIST", json_encode($sendByRegid));
}

/**
 * 同步用户id
 */
function syncUid($uid)
{

    // 更新用户id
    db('User')->where('uid', $uid)->update(['id' => $uid]);

}

/**
 *  发送极光通知
 * @param $uid 发给谁
 * @param $text 发什么
 */
function sendJpush($uid, $pushText)
{


    // 发通知
    $redis = get_redis();

    $sendByAlias = [
        'send_type' => 'sendByAlias',
        'send_data' => [
            'alert' => $pushText,
            'alias' => ["{$uid}"]
        ]
    ];

    $redis->lPush("JPUSH-SEND-LIST", json_encode($sendByAlias));

}

function getJpush()
{
    $masterSecret = config('jpush.masterSecret');
    $appKey = config('jpush.appKey');
    $rootDir = $_SERVER['DOCUMENT_ROOT'];
    $client = new JPush($appKey, $masterSecret, "$rootDir/../runtime/jipush.log");
    $pusher = $client->push();
    return $pusher;
}
